<script setup lang="ts">
import { useRoute } from 'vue-router'
import * as monaco from 'monaco-editor'
import { onMounted, reactive } from 'vue'
import { templateAdd, templateById, templateModify } from '@/api/system/generator/template'
import { Message, Modal } from '@arco-design/web-vue'
import router from '@/router'
import type { PageInfo, Result } from '@/tools/request'
import type { GeneratorFile, GeneratorTemplate } from '@/api/system/generator/generator'

const query = useRoute().query

const template = reactive({
  fileIndex: 1,
  form: {
    title: '',
    files: [{
      fileName: '',
      content: 'package main\n\nfunc main(){\n\n}',
      language: 'go'
    }] as GeneratorFile[]
  } as GeneratorTemplate,
  language: monaco.languages.getLanguages(),
  editors: [{
    editorObj: null as null | any,
    changeLanguage: null as null | any,
    getValue: null as null | any
  }],
  addFile: () => {
    template.form.files!.push({
      fileName: '',
      content: ''
    } as GeneratorFile)
    template.editors.push({
      editorObj: null,
      changeLanguage: null,
      getValue: null
    })
    const t = setTimeout(() => {
      initEditor(template.fileIndex++)
      clearTimeout(t)
    }, 10)
  },
  changeTheme: (value: string) => {
    monaco.editor.setTheme(value)
  },
  fileRemove: (index: number) => {
    console.log('删除Index：', index)
    template.form.files!.splice(index, 1)
    template.fileIndex--
  },
  submit: ({ values, errors }: any) => {
    if (errors) {
      return
    }
    template.editors.forEach((val: any, index: number) => {
      template.form.files![index].content = val.getValue()
    })
    if (query.id) {
      templateModify(template.form).then(() => {
        Modal.confirm({
          content: '修改模板成功，是否返回模板管理页面',
          onOk: () => {
            router.back()
          }
        })
      })
      return
    }
    templateAdd(template.form).then(() => {
      Modal.confirm({
        content: '添加模板成功，是否返回模板管理页面',
        onOk: () => {
          router.back()
        }
      })
    })
  }
})

//初始化代码编辑器
const initEditor = (index: number) => {
  const element = document.getElementById(`edit${index}`)!
  const editor = monaco.editor.create(element, {
    value: template.form.files![index].content!,
    language: template.form.files![index].language!,
    theme: 'vs-dark',
    automaticLayout: true
  })
  template.editors[index] = {
    editorObj: editor,
    getValue: () => editor.getValue(),
    changeLanguage: () => monaco.editor.setModelLanguage(editor.getModel()!, template.form.files![index].language!)
  }
}

onMounted(() => {
  if (query.id) {
    template.editors = []
    //@ts-ignore
    templateById(query.id).then((resp: Result<GeneratorTemplate>) => {

      const data = resp.data
      const files = data.files
      data.files = []
      template.form = data
      for (let i = 0; i < files!.length; i++) {
        //添加元素
        template.form.files!.push(files![i])
        template.editors.push({
          editorObj: null,
          changeLanguage: null,
          getValue: null
        })
        const t = setTimeout(() => {
          initEditor(i)
          clearTimeout(t)
        }, 20)
      }
      template.fileIndex = files!.length
    })
    return
  }

  //如果不是修改，则初始化第一个编辑器
  initEditor(0)
})

//全屏
const fullScreen = (id: number) => {
  const element = template.editors[id].editorObj.getContainerDomNode()
  element.requestFullscreen()
}

</script>

<template>
  <a-breadcrumb class="my-3">
    <a-breadcrumb-item>系统工具</a-breadcrumb-item>
    <a-breadcrumb-item @click="$router.push('/generator/template')" style="cursor: pointer">模板管理</a-breadcrumb-item>
    <a-breadcrumb-item v-if="query.id">模板创建</a-breadcrumb-item>
    <a-breadcrumb-item v-else>模板修改</a-breadcrumb-item>
  </a-breadcrumb>
  <a-layout-content>
    <a-card>
      <template #title>
        <template v-if="!query.id">
          模板创建
        </template>
        <template v-else>
          模板修改
        </template>
      </template>

      <a-form :model="template.form" @submit="template.submit" auto-label-width>
        <div>

          <a-space class="d-flex align-items-start mt-3">
            <a-button type="primary" @click="template.addFile">
              <template #icon>
                <IconPlus />
              </template>
              新建文件模板
            </a-button>
            <a-select default-value="vs-dark" placeholder="编辑器主题" style="width: 250px"
                      @change="template.changeTheme">
              <a-option active label="vs-dark" value="vs-dark" />
              <a-option label="vs" value="vs" />
              <a-option label="hc-black" value="hc-black" />
            </a-select>
            <a-form-item field="title" :rules="[{required:true,message:'模板名称不能为空'}]" validate-trigger="blur"
                         hide-asterisk hide-label>
              <a-input placeholder="模板名称" v-model="template.form.title" style="width: 260px" />
            </a-form-item>
            <a-button html-type="submit" class="bg-success text-white">
              <template #icon>
                <IconSave />
              </template>
              提交
            </a-button>

            <a-tooltip position="bottom">
              <template #content>
                <a-list>
                  <a-list-item class="info-hint">&lcub;&lcub;.TabName&rcub;&rcub; 数据库标明</a-list-item>
                  <a-list-item class="info-hint">&lcub;&lcub;.StructName&rcub;&rcub; 结构体标明</a-list-item>
                  <a-list-item class="info-hint">&lcub;&lcub;.CommentName&rcub;&rcub; 备注名</a-list-item>
                  <a-list-item class="info-hint">&lcub;&lcub;.Columns&rcub;&rcub; 字段列表</a-list-item>
                  <a-list-item class="info-hint">&lcub;&lcub;.GeneratorTableId&rcub;&rcub; 表ID</a-list-item>
                  <a-list-item class="info-hint">&lcub;&lcub;.ColumnName&rcub;&rcub; 字段名</a-list-item>
                  <a-list-item class="info-hint">&lcub;&lcub;.SqlType&rcub;&rcub; sqL类型</a-list-item>
                  <a-list-item class="info-hint">&lcub;&lcub;.StructType&rcub;&rcub; 结构体类型</a-list-item>
                  <a-list-item class="info-hint">&lcub;&lcub;.Title&rcub;&rcub; 字段名称（例如：Username 这里的值就是
                    用户名）
                  </a-list-item>
                  <a-list-item class="info-hint">&lcub;&lcub;.Search&rcub;&rcub; 是否搜索</a-list-item>
                  <a-list-item class="info-hint">&lcub;&lcub;.Edit&rcub;&rcub; 是否编辑</a-list-item>
                  <a-list-item class="info-hint">&lcub;&lcub;.Show&rcub;&rcub; 是否显示</a-list-item>
                  <a-list-item class="info-hint">&lcub;&lcub;.Condition&rcub;&rcub; 查询条件</a-list-item>
                </a-list>
              </template>
              <a-button>
                <template #icon>
                  <IconInfo />
                </template>
                变量
              </a-button>
            </a-tooltip>

            <a-tooltip position="bottom">
              <template #content>
                <a-list>
                  <a-list-item class="info-hint"> eq 如果arg1 == arg2则返回真</a-list-item>
                  <a-list-item class="info-hint"> ne 如果arg1 &ne; arg2则返回真</a-list-item>
                  <a-list-item class="info-hint"> lt 如果arg1 &lt; arg2则返回真</a-list-item>
                  <a-list-item class="info-hint"> le 如果arg1 &le; arg2则返回真</a-list-item>
                  <a-list-item class="info-hint"> gt 如果arg1 &gt; arg2则返回真</a-list-item>
                  <a-list-item class="info-hint"> ge 如果arg1 &ge; arg2则返回真</a-list-item>
                </a-list>
              </template>
              <a-button>
                <template #icon>
                  <IconInfo />
                </template>
                比较运算符
              </a-button>
            </a-tooltip>
            <a-tooltip position="bottom">
              <template #content>
                <a-list>
                  <a-list-item class="info-hint"> Add(num,num2) 加法</a-list-item>
                  <a-list-item class="info-hint"> Sub(num,num2) 加法</a-list-item>
                  <a-list-item class="info-hint"> ToUpper(text) 全部大写</a-list-item>
                  <a-list-item class="info-hint"> FirstLower(text) 首字母小写</a-list-item>
                  <a-list-item class="info-hint"> UpperToLine(text) 大写转小写加下划线</a-list-item>
                </a-list>
              </template>
              <a-button>
                <template #icon>
                  <IconInfo />
                </template>
                内置函数
              </a-button>
            </a-tooltip>
          </a-space>
        </div>

        <a-divider></a-divider>
        <div
          v-for="(v,i) in template.form.files"
          :key="i"
          class="my-3"
        >
          <a-row :gutter="20">
            <a-col :span="6">
              <a-form-item :field="`files.${i}.fileName`"
                           validate-trigger="blur"
                           :rules="[{required: true,message:'文件名不能为空'}]"
                           label="文件名"
                           hide-asterisk
              >
                <a-input v-model="template.form.files![i].fileName" />
              </a-form-item>
            </a-col>
            <a-col :span="6">
              <a-select default-value="go" v-model="template.form.files![i].language" allow-create allow-search
                        placeholder="编辑器语言" style="width: 250px"
                        @change="template.editors[i].changeLanguage">
                <a-option :label="v.id" :value="v.id" v-for="(v,i) in template.language" :key="i" />
              </a-select>
            </a-col>
            <a-col :span="6">
              <a-button class="bg-danger text-white" @click="template.fileRemove(i)">
                <template #icon>
                  <IconDelete />
                </template>
                删除模板
              </a-button>
            </a-col>
            <a-col>
              <div class="d-flex bg-success-subtle  position-relative" style="height: 400px">
                <div :id="`edit${i}`" class="w-100 h-100">
                </div>
                <a-button type="primary" class="position-absolute " style="right: 10px;bottom: 10px;z-index: 9999"
                          shape="circle"
                          @click="fullScreen(i)">
                  <template #icon>
                    <IconExpand />
                  </template>
                </a-button>
              </div>
            </a-col>
          </a-row>
        </div>

      </a-form>
    </a-card>
  </a-layout-content>
</template>

<style scoped lang="scss">
.arco-tabs-nav::before {
  border: none !important;
}

.info-hint {
  color: white;

  :deep(.info-hint) {
    color: black;
  }
}
</style>
